package com.ep.countdowntimer.timer;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import com.ep.countdowntimer.R;

/**
 * Created by Administrator on 2017/8/16.
 */

public class CountDownTimerImpl extends CountDownTimer {
    private TextView mTextView;
    /**
     * @param millisInFuture    The number of millis in the future from the call
     *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
     *                          is called.
     * @param countDownInterval The interval along the way to receive
     *                          {@link #onTick(long)} callbacks.
     */
    public CountDownTimerImpl(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onTick(long millisUntilFinished) {
        mTextView.setClickable(false);//开始计时设置按钮不可点击
        mTextView.setText(millisUntilFinished/1000+"秒后可重新发送");
        mTextView.setBackgroundResource(R.drawable.tv_code_press);

        //设置时间为红色，
        String text = mTextView.getText().toString();
        SpannableString spannableString=new SpannableString(text);
        ForegroundColorSpan span=new ForegroundColorSpan(Color.RED);
        String substring = text.substring(0, 2);
        if (isNumeric(substring)){
            spannableString.setSpan(span,0,2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }else {
            spannableString.setSpan(span,0,1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        mTextView.setText(spannableString);
    }

    @Override
    public void onFinish() {
        mTextView.setText("获取验证码");
        mTextView.setClickable(true);
        mTextView.setBackgroundResource(R.drawable.tv_code_nomol);
    }

    public CountDownTimerImpl(long millisInFuture, long countDownInterval, TextView textView) {
        super(millisInFuture, countDownInterval);
        mTextView = textView;
    }

    /**
     * 判断字符串是否为数字
     * @param str
     * @return
     */
    private  boolean isNumeric(String str){
        for (int i = 0; i < str.length(); i++){
            System.out.println(str.charAt(i));
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }
}
